package com.spring.lock;

import java.util.concurrent.atomic.AtomicReference;


/**
 * 简易CAS自旋锁，非公平锁，可重入锁. 应该也算悲观锁
 *
 * ioc 中没有使用到这个玩意
 */

public class CASLock {
	private AtomicReference<Thread> owner = new AtomicReference<>();
	private int count = 0;    // count 只会在锁定状态下修改，所以不需要原子性
	
	public void lock() {
		// 是否当前线程
		Thread thread = Thread.currentThread();
		if (thread == owner.get()) {
			count++;
			return;
		}
		
		while (!owner.compareAndSet(null, thread)) {
		
		}
	}
	
	
	public void unlock() {
		Thread thread = Thread.currentThread();
		if (thread == owner.get()) {
			if (count > 0) {
				count--;
			} else {
				owner.compareAndSet(thread, null);
			}
		}
	}
	
}

